package com.example.jdai.jdai.ui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jdai.jdai.MyApplication;
import com.example.jdai.jdai.R;
import com.example.jdai.jdai.config.Config;
import com.example.jdai.jdai.rest.BackRest;
import com.example.jdai.jdai.rest.SendCode;
import com.example.jdai.jdai.threeparty.SmsReceiver;
import com.example.jdai.jdai.util.DataAll;
import com.example.jdai.jdai.util.DataPhone;
import com.example.jdai.jdai.util.Tools;

import java.io.IOException;
import java.util.Map;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class PhoneActivity extends Activity implements BackRest.DoLong {

    @BindView(R.id.tb)
    TopBar tb;
    @BindView(R.id.bt_ok)
    Button btOk;
    @BindView(R.id.et_num)
    EditText etNum;
    @BindView(R.id.my_yzm)
    MyYzm btYzm;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.activity_phone)
    RelativeLayout activityPhone;
    @BindString(R.string.no_complete)
    String onComplete;
    ProgressDialog pd;
    @BindString(R.string.http_tip)
    String httpTip;
    @BindView(R.id.tv_forget)
    TextView tvForget;
    SmsReceiver mSMSBroadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phone);
        ButterKnife.bind(this);
        pd = new ProgressDialog(this);
        pd.setMessage(httpTip);
        pd.setCanceledOnTouchOutside(false);
        btYzm.setMyYzmClick(new MyYzm.MyYzmClick() {
            @Override
            public boolean click() {
                if (!etNum.getText().toString().isEmpty()) {
                    MyApplication.backRest.smsOk(etNum.getText().toString().trim(),btYzm);
                    return true;
                }
                Toast.makeText(PhoneActivity.this, "号码不能不为空", Toast.LENGTH_SHORT).show();
                return false;
            }
        });
        tb.setTopBarLisener(new TopBar.TopBarLisener() {
            @Override
            public void back() {
                finish();
                saveAll();
            }

            @Override
            public void more() {
                //finish();

            }
        });
        initData();
        smsGet();
    }

    @OnClick({R.id.tb, R.id.bt_ok, R.id.et_num, R.id.my_yzm, R.id.et_code, R.id.et_pwd,R.id.tv_forget})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tb:
                finish();
                break;
            case R.id.bt_ok:
                if ((!TextUtils.isEmpty(etPwd.getText().toString())) &&
                        (!TextUtils.isEmpty(etNum.getText().toString()))) {
                    DataAll.dataPhone.data.put(DataPhone.PHONE_CODE, "");
                    saveAll();
                    pd.show();
                    MyApplication.backRest.PhoneOk(PhoneActivity.this, etCode.getText().toString().trim());
                } else {
                    Toast.makeText(this, onComplete, Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.et_num:
                break;
            case R.id.my_yzm:
                MyApplication.backRest.smsOk(etNum.getText().toString().trim(),btYzm);
                break;
            case R.id.et_code:
                break;
            case R.id.et_pwd:

                break;
            case R.id.tv_forget:
                startActivity(new Intent(PhoneActivity.this,ForgetActivity.class));
                break;
        }
    }

    //    //获得验证码
//    void getCode(){
//        RestApi.CodeService service = MyApplication.retrofit.create(RestApi.CodeService.class);
//        SendCode send=new SendCode ();
//        send.data.put("tel",etNum.getText().toString().trim());
//        service.getCode(RestApi.getBody(send))
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Subscriber<GetData<String>>() {
//                    @Override
//                    public void onCompleted() {
//                        if (Config.ISDEBUG)
//                        Log.v("phone","complete");
//
//                    }
//                    @Override
//                    public void onError(Throwable e) {
//                        if (Config.ISDEBUG)
//                        Log.v("phone","complete");
//
//                    }
//                    @Override
//                    public void onNext(GetData<String> stringStringMap) {
//                        if (Config.ISDEBUG)
//                        Log.v("phone",new GsonBuilder().setPrettyPrinting().create().toJson(stringStringMap));
//                    }
//                });
//
//    }
    //ok按钮
    void okCommit() {
        //RestApi.PhoneService service = MyApplication.retrofit.create(RestApi.PhoneService.class);
        SendCode send = new SendCode();
        send.data.put("user_id", MyApplication.dataAll.data.get(DataAll.LOGIN_ID));
        send.data.put("tel", DataAll.dataPhone.data.get(DataPhone.PHONE_NUM));
        send.data.put("code", etCode.getText().toString());
        send.data.put("tel_pwd", DataAll.dataPhone.data.get(DataPhone.PHONE_PWD));
        Call call = MyApplication.okClient.newCall(Tools.getRequest(Config.PHONE_UP_URL, send));
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (Config.ISDEBUG)
                    Log.v("phone_error", e.toString());
                DataAll.dataPhone.data.put(DataPhone.PHONE_CODE, "");

                Tools.postToMain(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MyApplication.applicationContext, "验证码不正确", Toast.LENGTH_SHORT).show();

                    }
                });

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                int code = response.code();
                if (200 == code) {

                    if (Config.ISDEBUG)
                        Log.v("phone", response.body().string());
                    DataAll.dataPhone.data.put(DataPhone.PHONE_CODE, "ok");
                    Tools.postToMain(new Runnable() {
                        @Override
                        public void run() {
                            finish();
                        }
                    });

                } else {

                }

            }

        });
//        service.update(RestApi.getBody(send))
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Subscriber<GetData<Integer>>() {
//                    @Override
//                    public void onCompleted() {
//                        if (Config.ISDEBUG)
//                        Log.v("okbt","complete");
//                    }
//                    @Override
//                    public void onError(Throwable e) {
//                        if (Config.ISDEBUG)
//                        Log.v("okbt",e.toString());
//                        Toast.makeText(MyApplication.applicationContext,"验证码不正确",Toast.LENGTH_SHORT).show();
//                        DataAll.dataPhone.data.put(DataPhone.PHONE_MARK1,"");
//                    }
//                    @Override
//                    public void onNext(GetData<Integer> stringStringMap) {
//                        if (Config.ISDEBUG)
//                        Log.v("okbt",new GsonBuilder().setPrettyPrinting().create().toJson(stringStringMap));
//                        DataAll.dataPhone.data.put(DataPhone.PHONE_MARK1,"ok");
//                        finish();
//
//                    }
//                });
    }

    @Override
    protected void onDestroy() {
        saveAll();
        finish();
        super.onDestroy();
        this.unregisterReceiver(mSMSBroadcastReceiver);

    }

    @Override
    protected void onPause() {
        super.onPause();
        saveAll();
    }

    boolean saveAll() {
        DataAll.dataPhone.data.put(DataPhone.PHONE_NUM, etNum.getText().toString().trim());
        DataAll.dataPhone.data.put(DataPhone.PHONE_PWD, etPwd.getText().toString().trim());
        return DataAll.dataPhone.saveAll();
    }

    void initData() {
        String num="";
        if(TextUtils.isEmpty(DataAll.dataPhone.data.get(DataPhone.PHONE_NUM))) {
            num = MyApplication.dataAll.data.get(DataAll.HAS_LOGIN);
        }
        else {
            num = DataAll.dataPhone.data.get(DataPhone.PHONE_NUM);
        }
        etNum.setText(num);
        etNum.setSelection(num.length());
        etPwd.setText(DataAll.dataPhone.data.get(DataPhone.PHONE_PWD));
    }

    @Override
    public void doDone(int mark, Map str) {
        switch (mark){
            case 1:
                Toast.makeText(MyApplication.applicationContext, "手机需要验证码", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(PhoneActivity.this, YzmActivity.class);
                intent.putExtra("plat", 4);
                intent.putExtra("token", MyApplication.dataAll.data.get(DataAll.TMP));
                startActivity(intent);
                finish();
            case 0:
                pd.dismiss();
                finish();
                break;
            case 202:
                Toast.makeText(MyApplication.applicationContext,"手机号或密码错误",Toast.LENGTH_SHORT).show();
                pd.dismiss();
                break;
            case 203:
                Toast.makeText(MyApplication.applicationContext,"验证码发送达到上限",Toast.LENGTH_SHORT).show();
                pd.dismiss();
                break;
            case 207:
                Toast.makeText(MyApplication.applicationContext,"用户的的账户已被封，请明天再试",Toast.LENGTH_SHORT).show();
                pd.dismiss();
                break;
            case 208:
                Toast.makeText(MyApplication.applicationContext,"运营商网络异常，请稍后重试",Toast.LENGTH_SHORT).show();
                pd.dismiss();
                break;

        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
    void smsGet(){
        mSMSBroadcastReceiver = new SmsReceiver();
        //实例化过滤器并设置要过滤的广播
        IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
        intentFilter.setPriority(Integer.MAX_VALUE);
        //注册广播
        this.registerReceiver(mSMSBroadcastReceiver, intentFilter);
        mSMSBroadcastReceiver.setOnReceivedMessageListener(new SmsReceiver.MessageListener() {
            @Override
            public void onReceived(String message) {
                etCode.setText(message);
            }
        });
    }
}
